#include"mystdio.h"
#include<cstring>
#include<cstdlib>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

static MyFile* BuyFile(int fd,int flag)
{
    MyFile* f=(MyFile*)malloc(sizeof(MyFile));
    if(f==NULL)
    {
        perror("malloc");
        return NULL;
    }
    f->fileno=fd;
    f->flag=flag;
    memset(f->outbuffer,0,sizeof(f->outbuffer));
    f->fflush_method=LINE_FLUSH;
    f->bufferlen=0;
    return f;
}

MyFile* MyFopen(const char *path,const char *mode)
{
    int fd=-1,flag=0;
    if(strcmp(mode,"w")==0)
    {
        flag=O_CREAT|O_WRONLY|O_TRUNC;
        fd=open(path,flag,0666);
    }
    else if(strcmp(mode,"a")==0)
    {
        flag=O_CREAT|O_WRONLY|O_APPEND;
        fd=open(path,flag,0666);

    }
    else if(strcmp(mode,"r")==0)
    {
        flag=O_RDONLY;
        fd=open(path,flag);
    }
    else
    {
        
    }
    if(fd<0) return NULL;
    return BuyFile(fd,flag);
}
void MyFclose(MyFile* file)
{
    if(file->fileno<0) return;
    MyFFlush(file); //缓冲区存在的意义：减少系统调用的次数  
    close(file->fileno);
    free(file);
}
int MyFwrite(MyFile* file,void *str,int len)
{
    //1、拷贝
    memcpy(file->outbuffer+file->bufferlen,str,len);
    file->bufferlen+=len;

    //2、尝试判断是否满足刷新条件！
    if((file->fflush_method & LINE_FLUSH) && file->outbuffer[file->bufferlen-1]=='\n')
        MyFFlush(file);
    return 0;
}
void MyFFlush(MyFile* file)
{
    if(file->bufferlen<=0) return;
    // 把数据从用户拷贝到内核文件缓冲区中
    int n=write(file->fileno,file->outbuffer,file->bufferlen);
    (void)n;
    // 操作系统将数据立马刷新到外设里
    fsync(file->fileno); 
    file->bufferlen=0;
}
